package com.dhz.common.queue.guava;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * <p>Guava的事件总线服务使用的是ThreadPoolExecutor来实现任务调度监听，在应用关闭时，不能狗正常的关闭掉EventBus服务中启用的线程，将会抛出如下异常信息：</p>
 * <p>
 *     10-Oct-2015 11:16:11.339 WARNING [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [v1] appears to have started a thread named [pool-10-thread-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 *     sun.misc.Unsafe.park(Native Method)
 *     java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
 *     java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
 *     java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
 *     java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
 *     java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
 *     java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 *     java.lang.Thread.run(Thread.java:745)
 * </p>
 *
 * <p>解决：添加一个监听器，在应用关闭时，停止掉所有的GuavaEventBus启用的线程</p>
 *
 * @author FY
 */
public class ShutdownListener implements ServletContextListener {
    private static final Logger logger = LoggerFactory.getLogger(ShutdownListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        GuavaQueueManager.shutdown();
    }
}
